package com.wyy.service.impl;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.wyy.error.BusinessException;
import com.wyy.error.EnumBusinessError;
import com.wyy.pojo.AppreciatesOrder;
import com.wyy.service.AlipayService;
import com.wyy.service.OrderService;
import com.wyy.util.MyUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: gytcb
 * @author: 吴磊
 * @create: 2021-06-26 14:55
 */
@Service
public class AlipayServiceImpl implements AlipayService {
    //d4fcc188dcaece57
    @Autowired
    private OrderService orderService;

    /**
     * 当面付
     *
     * @param appreciatesOrder
     */
    @SneakyThrows
    @Override
    public Map<String, Object> FaceTofACEPay(AppreciatesOrder appreciatesOrder) {
        MyUtil myUtil = new MyUtil();
        //获取二维码的同时要生成订单号
        String orderId = myUtil.getUUID();
        appreciatesOrder.setOrderId(orderId);
        //获取当前日期
        String orderDate = myUtil.getCurrentDetailedTime();
        appreciatesOrder.setOrderDate(orderDate);
        //设置订单为未支付状态
        appreciatesOrder.setOrderStatus(0);

        Integer integer;
        HashMap<String, Object> map = new HashMap<>();
        AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace().preCreate("树洞赞赏", orderId, "" + appreciatesOrder.getOrderAmount());
        if (ResponseChecker.success(response)) {
            String qrCode = response.getQrCode();
            map.put("qrCode", qrCode);
            map.put("orderId", orderId);
            integer = orderService.insertOrder(appreciatesOrder);
        } else {
            integer = 0;
            map.put("qrCode", "");
            map.put("orderId", "");
        }
        if (integer <= 0) {
            throw new BusinessException(EnumBusinessError.UNKNOWN_ERROR, "生成二维码失败");
        }
        return map;
    }

    /**
     * 支付异步回调
     *
     * @param mapParams
     * @return
     */
    @SneakyThrows
    @Override
    public String notifyUrl(Map<String, String> mapParams) {
        //验签
        if (Factory.Payment.Common().verifyNotify(mapParams)) {
            //验证用户的支付结果
            String trade_status = mapParams.get("trade_status");
            if ("TRADE_SUCCESS".equals(trade_status)) {
                //这里可以根据业务更新订单支付状态.....
                AppreciatesOrder appreciatesOrder = new AppreciatesOrder();
                String orderId = (String) mapParams.get("out_trade_no");
                appreciatesOrder.setOrderId(orderId);
                appreciatesOrder.setOrderStatus(1);
                orderService.updateOrder(appreciatesOrder);
                return "success";
            }
        } else {
            return "fail";
        }
        return "fail";
    }
}
